<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('流程标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('流程标题')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请人')" prop="userId">
            <UserSelect v-model="form.userId" :placeholder="$t('申请人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请部门')" prop="deptId">
            <DeptSelect v-model="form.deptId" :placeholder="$t('申请部门')" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('申请时间')" prop="applyTime">
            <el-date-picker
              v-model="form.applyTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('申请时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              :rows="8"
              :placeholder="$t('备注')"
              maxlength="2000"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="area-header">
        <span class="area-header-title">{{ $t('申请明细') }}</span>
      </div>
      <el-table :data="form.demandDetaileds" border class="nowrapTable formTable">
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('申请岗位')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('申请岗位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'demandDetaileds.' + scope.$index + '.postId'" :rules="demandDetailedsCheck.postId">
              <el-select v-model="scope.row.postId" value="" :placeholder="$t('申请岗位')" clearable>
                <el-option
                  v-for="dict in initDict.postList"
                  :key="dict.id"
                  :label="$t(dict.postName)"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('申请人数')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('申请人数') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'demandDetaileds.' + scope.$index + '.userNum'" :rules="demandDetailedsCheck.userNum">
              <el-input v-model="scope.row.userNum" :placeholder="$t('申请人数')" show-word-limit maxlength="5" onkeyup="value=value.replace(/[^\d]/g,'')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('期望到岗日期')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('期望到岗日期') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'demandDetaileds.' + scope.$index + '.arrivalDate'" :rules="demandDetailedsCheck.arrivalDate">
              <el-date-picker
                v-model="scope.row.arrivalDate"
                clearable
                style="width: 200px"
                type="date"
                value-format="yyyy-MM-dd"
                :placeholder="$t('期望到岗日期')"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('申请理由')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('申请理由') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item
              :prop="'demandDetaileds.' + scope.$index + '.applicationReasons'"
              :rules="demandDetailedsCheck.applicationReasons"
            >
              <dict-select
                v-model="scope.row.applicationReasons"
                dictionary="hr_application_reasons"
                :placeholder="$t('申请理由')"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('备注')" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="'demandDetaileds.' + scope.$index + '.remarks'" :rules="rules.remarks">
              <el-input
                v-model="scope.row.remarks"
                :placeholder="$t('备注')"
                type="textarea"
                maxlength="2000"
                :autosize="{ minRows: 1, maxRows: 10}"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" width="60px">
          <template slot-scope="scope">
            <el-button size="small" type="text" icon="el-icon-delete" @click="delRow(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addRow">{{ $t('添加') }}</el-button>
      </div>

      <!--文件-->
      <FileTable :list.sync="form.fileList" :data-type="dataType" :btn-show="!otherBtnHide" />

    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn ref="formBtn" :bus-data="form" has-permi="hr:demand" :menu-key="menuKey" />
    </div>
  </div>
</template>

<script>
import { saveHrDemand, getHrDemand } from '@/api/oa/hr/hrDemand'
import { delHrDemandDetailed } from '@/api/oa/hr/hrDemandDetailed'
import { listPost } from '@/api/system/post'

export default {
  components: {
  },
  data() {
    return {
      // 菜单标识
      menuKey: this.$t('hr_demand'),
      otherBtnHide: false,
      // 表单参数
      form: {
        demandDetaileds: [],
        fileList: []
      },
      // 表单校验
      rules: {
        actTitle: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], userId: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], deptId: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], applyTime: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ]
      },
      demandDetailedsCheck: {
        postId: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        arrivalDate: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        applicationReasons: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        userNum: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
      },
      // 遮罩层
      loading: false,
      dataType: 'hr_demand',
      // 操作按钮默认不展示
      buttonShow: true,
      initDict: {
        postList: []
      }
    }
  },
  created() {
    this.initData()
    this.$bus.$emit('async_done')
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      if (data != null && data.id !== undefined) {
        this.loading = true
        getHrDemand(data.id).then(response => {
          this.form = response.data
          this.loading = false
        })
      } else {
        this.reset()
        this.loading = false
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        actId: undefined,
        actStatus: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        actTitle: undefined,
        userId: undefined,
        deptId: undefined,
        applyTime: undefined,
        remark: undefined,
        demandDetaileds: [],
        fileList: []
      }

      this.initReset()
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm: function(type) {
      if (this.form.demandDetaileds === undefined || this.form.demandDetaileds === null || this.form.demandDetaileds.length === 0) {
        this.msgError(this.$t('至少一条明细'))
        return
      }
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(valid => {
          // 验证数据
          if (valid) {
            // 弹出遮罩层
            this.loading = true
            // 保存数据
            saveHrDemand(this.form).then(response => {
              if (response.code === 200) {
                // 点击的按钮是保存并启动流程
                if (type === 'process') {
                  // 启动流程
                  this.startProcess(response.data)
                  // 点击的仅保存
                } else {
                  this.msgSuccess(this.$t('保存成功'))
                  // 关闭form页面
                  this.closeForm()
                }
                resolve()
              } else {
                this.msgError(response.msg)
                this.loading = false
                reject()
              }
            })
          } else {
            reject()
            this.locationError(document)
          }
        })
      })
    },
    // 启动流程
    startProcess: function(dataId) {
      this.loading = false
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      processData.title = this.form.actTitle
      // 业务表名
      processData.dataTable = 'hr_demand'
      // 业务ID
      processData.dataId = dataId.id
      // 业务表单地址(待办页面需要打开的页面)
      processData.formPath = '@/views/oa/hr/demand/hrDemandForm'
      processData.viewPath = '@/views/oa/hr/demand/hrDemandView'
      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = this.menuKey
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        this.closeForm()
      })
    },
    // 添加出差事由
    addRow() {
      const row = {
        id: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        demandId: undefined,
        postId: undefined,
        userNum: undefined,
        arrivalDate: undefined,
        applicationReasons: undefined,
        remarks: undefined
      }
      this.form.demandDetaileds.push(row)
    },
    // 删除出差事由
    delRow(index, row) {
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        }).then(function() {
          return delHrDemandDetailed(id)
        }).then(() => {
          this.form.demandDetaileds.splice(index, 1)
          return this.msgSuccess(this.$t('删除成功'))
        }).catch(function() {
        })
      } else {
        this.form.demandDetaileds.splice(index, 1)
      }
    },
    initData() {
      // 岗位信息
      listPost({}).then(res => {
        this.initDict.postList = res.rows
      })
    },
    initReset() {
      this.form.userId = this.$store.state.user.userId
      // 获取当前时间
      const now = new Date()
      const year = now.getFullYear() // 得到年份
      let month = now.getMonth() // 得到月份
      let date = now.getDate() // 得到日期
      month = month + 1
      month = month.toString().padStart(2, '0')
      date = date.toString().padStart(2, '0')
      this.form.applyTime = `${year}-${month}-${date}`
    }

  }

}
</script>
